//
//  selectContactViewController.m
//  TTAddressBook
//


//  Created by wangming on 12-1-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "selectContacts.h"
#import "selectTableCell.h"
#import "CommTools.h"
#import <QuartzCore/QuartzCore.h>

#define TABLEVIEW_TAG 10
#define POPVIEW_IMAGEVIEW_TAG 11
#define POPVIEW_LABEL_TAG 12

#define UISelectContacts_GreenPopLabel @"contacts_green.png"
//
@implementation selectContacts
@synthesize filteredListContent,contactList,mytableView,showtype;
@synthesize selectContact;
#pragma mark - View lifecycle

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{ 

}
-(void)sendMessage:(id)sender{
    [MyClass getInstance].PersonMarkList = nil;
    if ([MyClass getInstance].personMarkList) {
        [[MyClass getInstance].personMarkList removeAllObjects];
    }
    else
    {
        [MyClass getInstance].personMarkList = [[NSMutableArray alloc] init];
    }
    
    NSMutableArray* arrCheckList=[[NSMutableArray alloc] init];
    for (NSMutableDictionary * dict  in contactList) {
        if ([[dict objectForKey:@"check"] isEqual:@"true"]) {
            [arrCheckList addObject:dict];
            [[MyClass getInstance].personMarkList addObject:dict];
        }
    }

    composeMessageViewController *view = [[composeMessageViewController alloc] initWithContact:arrCheckList];
    view.isSelectContacts2sms = YES;
    [self.navigationController pushViewController:view animated:YES];
    [view release];
    [arrCheckList release];
    
}
-(void)ShowContactOptMenu{
    //[self CreateClearBackBtn:0.80:[UIColor blackColor]];
    ContactOptMenuview = [[UIView alloc] initWithFrame:CGRectMake(0, 435, 320, 45)];
    ContactOptMenuview.backgroundColor = [UIColor blackColor];
    ContactOptMenuview.alpha = 0.92;
    ContactOptMenuview.tag =  MENUVIEW_TAG;
    
    btnFreeSms = [UIButton buttonWithType:UIButtonTypeCustom];
    btnFreeSms.frame = CGRectMake(0, 10, 75, 25);
    [btnFreeSms setTitle: @"发送信息" forState:(UIControlStateNormal)];
    btnFreeSms.alpha  = 1.;
    extern double  globalRed,globalGreen,globalBlue;
    btnFreeSms.backgroundColor =[UIColor colorWithRed:globalRed/255 green:globalGreen blue:globalBlue/255 alpha:1.0];
    btnFreeSms.titleLabel.font = [UIFont systemFontOfSize:11];
    [btnFreeSms addTarget:self action:@selector(sendMessage:) forControlEvents:UIControlEventTouchUpInside];    
    btnFreeSms.layer.cornerRadius = 10;/////////////////////////自己试着改变这个值，看看各个不同的效果。现在的设置是画了个圆圈。
    btnFreeSms.layer.masksToBounds = YES;//////////////////////////  
    [ContactOptMenuview addSubview:btnFreeSms];
    [self.navigationController.view addSubview:ContactOptMenuview];
    [ContactOptMenuview release];
}

- (id)initWithMessageContacts:(NSMutableArray*)selects{
    if (self = [super init]) {
        {
            startAt=0;
            type=1;
            showtype=2;
            self.selectContact = selects;
            NSDictionary * ret = [[MyClass getInstance] getMembers: nil ofType:nil inOrder:1 startAt:startAt limit:15 searchWith:nil];
            if ([[ret objectForKey:@"total"] intValue] > 0) {
                NSArray * arr = [ret objectForKey:@"list"];
                if (self.contactList) {
                    if (type==1){
                        [self.contactList removeAllObjects]; 
                        startAt=[arr count];
                    }
                    else
                        startAt+=[arr count];
                }
                else{
                    self.contactList = [[[NSMutableArray alloc] init] autorelease];
                    startAt=[arr count];
                }
                [self.contactList addObjectsFromArray:arr];
            }
        }
        if (selectContact) 
        {
            for (NSDictionary *dict in self.contactList) {
                if ([selectContact count]>0) 
                {
                    NSString* strMark = [dict objectForKey:@"personMark"];
                    BOOL find=NO;
                    NSDictionary* tmpDict = nil;
                    for (tmpDict in selectContact) {
                        NSString* strMarkTmp = [tmpDict objectForKey:@"personMark"];
                        if ([strMark isEqual:strMarkTmp]) 
                        {
                            find=YES;
                            break;
                        }
                    }
                    if (find)
                    {
                        [selectContact removeObject:tmpDict];
                        [dict setValue:@"true" forKey:@"check"];
                    }
                    else
                        [dict setValue:@"false" forKey:@"check"];
                }
                else
                {
                    break;
                }
            }
        }
        selectedRow = -1;
        [self setHidesBottomBarWhenPushed:YES];
    }
    return self;
}


- (id)initWithContacts:(NSMutableArray*)contacts{
    self.selectContact=nil;
    if (self = [super init]) {
        if (contacts) {
            self.contactList = contacts;
            showtype=1;
        }
        else{
            startAt=0;
            type=1;
            showtype=2;
            NSDictionary * ret = [[MyClass getInstance] getMembers: nil ofType:nil inOrder:1 startAt:startAt limit:15 searchWith:nil];
            if ([[ret objectForKey:@"total"] intValue] > 0) {
                NSArray * arr = [ret objectForKey:@"list"];
                if (self.contactList) {
                    if (type==1){
                        [self.contactList removeAllObjects]; 
                        startAt=[arr count];
                    }
                    else
                        startAt+=[arr count];
                }
                else{
                    self.contactList = [[[NSMutableArray alloc] init] autorelease];
                    startAt=[arr count];
                }
                [self.contactList addObjectsFromArray:arr];
            }
        }
        selectedRow = -1;
        [self setHidesBottomBarWhenPushed:YES];
    }
    return self;
}

- (void)dealloc{   
    [filteredListContent removeAllObjects];
    self.filteredListContent = nil;    
    [searchDC release];  
    self.contactList=nil;
    [super dealloc];
}
-(void)goBackClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)okClick{
    //[[MyClass getInstance] setPersonMarkList:nil];
    if ([MyClass getInstance].personMarkList) {
        [[MyClass getInstance].personMarkList removeAllObjects];
    }
    else
    {
        [MyClass getInstance].personMarkList = [[NSMutableArray alloc] init];
    }
    NSMutableArray* arrCheckList=[[NSMutableArray alloc] init];
    for (NSMutableDictionary * dict  in contactList) {
        if ([[dict objectForKey:@"check"] isEqual:@"true"]) {
            [arrCheckList addObject:dict];
        }
    }
    if (selectContact && selectContact.count>0) {
        [[MyClass getInstance].personMarkList addObjectsFromArray:selectContact];
    }
    if (arrCheckList) {
         [[MyClass getInstance].personMarkList addObjectsFromArray :arrCheckList];
    }
    NSLog(@"%@",[MyClass getInstance].personMarkList);
    [self.navigationController popViewControllerAnimated:YES];
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    UIView* selfView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
    selfView.backgroundColor = [UIColor whiteColor];
    self.view = selfView;
    [selfView release];
  
    mytableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
	mytableView.tag = TABLEVIEW_TAG;
	// set the autoresizing mask so that the table will always fill the view
	mytableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
	
	// set the cell separator to a single straight line.
	mytableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	// set the tableview delegate to this object and the datasource to the datasource which has already been set
	mytableView.delegate = self;
	mytableView.dataSource = self;
	//tableView.sectionIndexMinimumDisplayRowCount=10;
    	// set the tableview as the controller view
	[self.view addSubview:mytableView];    
    // Create a search bar
//	selSearchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
//	selSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
//    //set keyboard type
//    selSearchBar.keyboardType = UIKeyboardTypeASCIICapable;
//    //set ascii lowwercase
//	selSearchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
//    selSearchBar.delegate = self;
//	mytableView.tableHeaderView = selSearchBar;
//    
//	// Create the search display controller
//	searchDC = [[UISearchDisplayController alloc] initWithSearchBar:selSearchBar contentsController:self];
//	searchDC.searchResultsDataSource = self;
//	searchDC.searchResultsDelegate = self;
//    searchDC.delegate = self;
	[mytableView release];        
    
    UIBarButtonItem *goBackButton = [[UIBarButtonItem alloc]
                                     initWithTitle:@"返回"
                                     style:UIBarButtonItemStylePlain
                                     target:self
                                     action:@selector(goBackClick)];
    self.navigationItem.leftBarButtonItem = goBackButton;
    if (showtype==2) {
        UIBarButtonItem *okButton = [[UIBarButtonItem alloc]
                                         initWithTitle:@"确定"
                                         style:UIBarButtonItemStylePlain
                                         target:self
                                         action:@selector(okClick)];
        self.navigationItem.rightBarButtonItem = okButton;
    }
    [goBackButton release];
}

//
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];    
    self.navigationItem.title = @"选择成员";
    checkCount = 0;
}
-(void)viewWillAppear:(BOOL)animated{
    [self ShowContactOptMenu];
    ContactOptMenuview.hidden = YES;
    if (checkCount > 0 && showtype==1)
    {
        ContactOptMenuview.hidden = NO;
        [self.view bringSubviewToFront:ContactOptMenuview];
        NSString* str2 =[NSString stringWithFormat:@"发送信息(%d)",checkCount];
        [btnFreeSms setTitle: str2 forState:(UIControlStateNormal)];
    }
    else
        ContactOptMenuview.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    for (UIView *subview in self.navigationController.view.subviews) {
        if (subview.tag == MENUVIEW_TAG)              
            [subview removeFromSuperview];
    }
}
//
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

//
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
///
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    if(tableView.tag == TABLEVIEW_TAG)
    {
        return [self.contactList count];
    }
    return [self.filteredListContent count];
}
//
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    static NSString *CellIdentifier = @"Cell";
    
    selectTableCell *cell = (selectTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[selectTableCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
		cell.textLabel.font = [cell.textLabel.font fontWithSize:17];
    }
	
	cell.accessoryType = UITableViewCellAccessoryNone;
    [cell setChecked:NO];
    {        
        for (UIView *subview in cell.subviews) {
            if (subview.tag == 1001)              
                [subview removeFromSuperview];
        }
        //显示联系人，头像等信息。
        if (tableView.tag== TABLEVIEW_TAG)
        {            
            
            NSDictionary *dict = [self.contactList objectAtIndex:row];  
            
            if (selectContact) {
                if ([selectContact count]>0) {
                    NSString* strMark = [dict objectForKey:@"personMark"];
                    BOOL find=NO;
                    NSDictionary* tmpDict = nil;
                    for (tmpDict in selectContact) {
                        NSString* strMarkTmp = [tmpDict objectForKey:@"personMark"];
                        if ([strMark isEqual:strMarkTmp]) 
                        {
                            find=YES;
                            break;
                        }
                    }
                    if (find)
                    {
                        [selectContact removeObject:tmpDict];
                        [dict setValue:@"true" forKey:@"check"];
                    }
                }
            }
            
            if ([[dict allKeys] containsObject:@"check"]){
                if ([[dict objectForKey:@"check"] isEqual:@"true"]) {
                    [cell setChecked:YES];
                }
                
            }
            
            //infoItem = [nameSection objectAtIndex:row];    
            UILabel* lab1; 
            lab1 = [[UILabel alloc] init];
            lab1.frame = CGRectMake(100, 5, 160, 22);
            lab1.text = [dict objectForKey:@"personShowName"];
            lab1.font = [UIFont boldSystemFontOfSize:19];
            lab1.backgroundColor = [UIColor clearColor];           
            lab1.tag = 1001;
            [cell addSubview:lab1];
            [lab1 release]; 
        }
        else{//搜索结果
            //infoItem = [self.filteredListContent objectAtIndex:indexPath.row];
            NSDictionary *dict = [self.filteredListContent objectAtIndex:row];
            [cell textLabel].textColor = [UIColor clearColor];
            UILabel* lab; 
            lab = [[UILabel alloc] initWithFrame:CGRectMake(100, 13, 160, 22)];
            lab.tag = 1001;
            lab.text = [dict objectForKey:@"personShowName"];
            lab.font = [UIFont boldSystemFontOfSize:19];
            lab.backgroundColor = [UIColor clearColor];           
            [cell addSubview:lab];
            [lab release];            
        }         
//        
        UIImageView* imgview=[[UIImageView alloc] initWithFrame:CGRectMake(45, 5, 34, 34)];
        imgview.tag=1001;
        imgview.image = [UIImage imageNamed:UIContacts_Contacts_icon];  
        [cell addSubview:imgview];
    } 
	
    return cell;
}

//#pragma mark - ???
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary* infoItem = nil;
    selectTableCell *cell = (selectTableCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (tableView.tag == TABLEVIEW_TAG)
	{
        infoItem = [self.contactList objectAtIndex:indexPath.row];
    }
	else
	{
        infoItem = [self.filteredListContent objectAtIndex:indexPath.row];
    }
    if ( [[infoItem allKeys] containsObject:@"check"]){
        if ([[infoItem objectForKey:@"check"] isEqual:@"true"]) {
            [infoItem setObject:@"false" forKey:@"check"];
            if (checkCount>0)  
                checkCount--;
            [cell setChecked:NO];
            /*
            NSMutableDictionary* tmpDict = nil;
                for (NSMutableDictionary* dict in [MyClass getInstance].personMarkList ) {
                    if ([[infoItem objectForKey:@"personMark"] isEqual:[dict objectForKey:@"personMark"]]) 
                    {
                        tmpDict = dict;
                        break;
                    }
                }
            if (tmpDict) {
                [[MyClass getInstance].personMarkList removeObject:tmpDict];
            }
             */
        }
        else{
            [infoItem setObject:@"true" forKey:@"check"];
            checkCount++;
            [cell setChecked:YES];
        }
        
    }
    else
    {
        [infoItem setObject:@"true" forKey:@"check"];
        checkCount++;
        [cell setChecked:YES];
    }
    
	[tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (checkCount > 0 && showtype==1)
    {
        ContactOptMenuview.hidden = NO;
        [self.view bringSubviewToFront:ContactOptMenuview];
        NSString* str2 =[NSString stringWithFormat:@"发送信息(%d)",checkCount];
        [btnFreeSms setTitle: str2 forState:(UIControlStateNormal)];
    }
    else
        ContactOptMenuview.hidden = YES;
    
}

//#pragma mark -
//#pragma mark Content Filtering
//
- (void)filterContentForSearchText:(NSString*)searchText
{
//	/*
//	 Update the filtered array based on the search text and scope.
//	 */
//	[filteredListContent removeAllObjects]; // First clear the filtered array.
//    if ([searchText length] == 0) {
//        self.filteredListContent = nil;
//    }else{
//        self.filteredListContent = (NSMutableArray*)[[ModelEngine getInstance] search:searchText keyboard:0];
//    }
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString];    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

#pragma mark -
#pragma mark UISearchBarDelegate Delegate Methods

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{    
    selectedRow = -1;
    [searchBar setShowsCancelButton:YES animated:YES];    
    for(UIView *subView in searchBar.subviews){        
        if([subView isKindOfClass:UIButton.class]){            
            [(UIButton*)subView setTitle:@"列表" forState:UIControlStateNormal];
            [(UIButton*)subView setBackgroundImage:[UIImage imageNamed:@"dialog_on.png"] forState:UIControlStateNormal];
        }        
    }
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    selectedRow = -1;
    UITableView* table = (UITableView*)[self.view viewWithTag:TABLEVIEW_TAG];
    [table reloadData];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (self.showtype==2)
    if (scrollView.contentOffset.y+scrollView.frame.size.height-40 > scrollView.contentSize.height) {
       
        NSDictionary * ret = [[MyClass getInstance] getMembers: nil ofType:nil inOrder:1 startAt:startAt limit:15 searchWith:nil];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            NSArray * arr = [ret objectForKey:@"list"];
            if (self.contactList) {
//                if (type==1){
//                    [self.contactList removeAllObjects]; 
//                    startAt=[arr count];
//                }
//                else
                    startAt+=[arr count];
            }
            else{
                self.contactList = [[[NSMutableArray alloc] init] autorelease];
                startAt=[arr count];
            }
            [self.contactList addObjectsFromArray:arr];
        }
        
        if (selectContact) 
        {
            for (NSDictionary *dict in self.contactList) {
                if ([selectContact count]>0) 
                {
                    NSString* strMark = [dict objectForKey:@"personMark"];
                    BOOL find=NO;
                    NSDictionary* tmpDict = nil;
                    for (tmpDict in selectContact) {
                        NSString* strMarkTmp = [tmpDict objectForKey:@"personMark"];
                        if ([strMark isEqual:strMarkTmp]) 
                        {
                            find=YES;
                            break;
                        }
                    }
                    if (find)
                    {
                        [selectContact removeObject:tmpDict];
                        [dict setValue:@"true" forKey:@"check"];
                    }
                    else
                        [dict setValue:@"false" forKey:@"check"];
                }
                else
                {
                    break;
                }
            }
        }

        [mytableView reloadData];
    }
}
@end
